package com.itheima.im.socket.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.webkit.URLUtil;

import static com.itheima.im.socket.provider.ContractsTable.TABLE_NAME;

/**
 * 1. 提供对数据库的CRUB操作
 * 2. 需要去注册
 */

public class ContractProvider extends ContentProvider {
	private static final String AUTHORITY = "com.itheima.im.socket.provider.ContractProvider";

	//1. 定义一个Uri 常量
	public static final Uri CONTRACT=Uri.parse("content://"+AUTHORITY+"/"+ TABLE_NAME);
	private DBhelper dBhelper;
	private SQLiteDatabase db;

	@Override
	public boolean onCreate() {
		dBhelper = new DBhelper(getContext());
		return dBhelper==null?false:true;
	}

	private static UriMatcher uriMatcher = null;
	private static final int MATCHCODE = 200;// 成功匹配

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(AUTHORITY, TABLE_NAME,MATCHCODE);
	}

	@Nullable
	@Override
	public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
		// 这里可以根据不同的编码对应不同的表
       if (uriMatcher.match(uri)==MATCHCODE){
           db = dBhelper.getReadableDatabase();
	       return db.query(TABLE_NAME,null,selection,selectionArgs,null,null,null);
       }
		return null;
	}

	@Nullable
	@Override
	public String getType(@NonNull Uri uri) {
		return null;
	}

	@Nullable
	@Override
	public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
		db = dBhelper.getReadableDatabase();
		long num=db.insert(TABLE_NAME,null,values);
        return 	Uri.withAppendedPath(uri,num+"");
	}

	@Override
	public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
		return 0;
	}

	@Override
	public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
		return 0;
	}
}
